﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Pampa.Grid.Core.Filters;
using Pampa.MVC.Fluent.Common;

namespace Pampa.MVC.Fluent.Grid
{
    public class FilterBuilder : AbstractBuilder
    {
        protected string _property;
        protected GroupFilter _rootFilter;
        protected SimpleFilter _currentFilter;
        protected bool _orChain;

        protected FilterBuilder(GroupFilter rootFilter)
        {
            _rootFilter = rootFilter;

            if (rootFilter is OrGroupFilter)
                _orChain = true;
            else
                _orChain = false;
        }

        internal OrGroupFilter Or()
        {
            if (_orChain)
            {
                return (OrGroupFilter)_rootFilter;
            }
            else
            {
                var newGroupFilter = new OrGroupFilter();
                newGroupFilter.AddFilter(_rootFilter);
                return newGroupFilter;
            }
        }

        internal AndGroupFilter And()
        {
            if (_orChain)
            {
                var newGroupFilter = new AndGroupFilter();
                newGroupFilter.AddFilter(_rootFilter);
                return newGroupFilter;
            }
            else
            {
                return (AndGroupFilter)_rootFilter;
            }
        }

        protected void AddFilter(OperationType operationType, object value)
        {
            _currentFilter = new SimpleFilter();
            _currentFilter.Field = _property;
            _currentFilter.Operation = operationType;
            _currentFilter.Value = value;

            _rootFilter.AddFilter(_currentFilter);
        }
    }

    public class FilterBuilder<T, TEntity> : FilterBuilder
    {
        public FilterBuilder(GroupFilter rootFilter, Expression<Func<T, TEntity>> property) : base(rootFilter)
        {
            _property = GetId(property);
        }
    }
}
